package zhuanyeshixi2.basic.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zhuanyeshixi2.basic.domain.User;
import zhuanyeshixi2.basic.global.GlobalEnum;
import zhuanyeshixi2.basic.mapper.UserMapper;
import zhuanyeshixi2.basic.service.UserService;
import zhuanyeshixi2.basic.vo.BasicMsg;
import zhuanyeshixi2.basic.vo.UserVo;

import java.util.Date;
import java.util.Arrays;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public BasicMsg login(UserVo userVo) {
        try {
            User user = userMapper.selectByUsernameAndPassword(userVo.getUsername(), userVo.getPassword());

            if (user == null) {
                return BasicMsg.fail(GlobalEnum.ErrorCode.USER_NOT_EXISTS, "用户名或密码错误");
            }

            UserVo responseUser = new UserVo();
            responseUser.setUserId(user.getUserId());
            responseUser.setUsername(user.getUsername());
            responseUser.setEmail(user.getEmail());
            responseUser.setRealName(user.getRealName());
            responseUser.setPhone(user.getPhone());

            // 获取用户角色并设置到返回对象中
            List<String> roles = userMapper.selectRolesByUsername(user.getUsername());
            responseUser.setRoles(roles);

            return BasicMsg.success(responseUser);

        } catch (Exception e) {
            return BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "登录失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public BasicMsg register(UserVo userVo) {
        try {
            User existingUser = userMapper.selectByUsername(userVo.getUsername());

            if (existingUser != null) {
                return BasicMsg.fail(GlobalEnum.ErrorCode.USER_ALREADY_EXISTS, "用户名已存在");
            }

            User newUser = new User();
            newUser.setUsername(userVo.getUsername());
            newUser.setPassword(userVo.getPassword());
            newUser.setEmail(userVo.getEmail());
            newUser.setRealName(userVo.getRealName() != null ? userVo.getRealName() : userVo.getUsername());
            newUser.setPhone(userVo.getPhone());
            newUser.setCreatedAt(new Date());
            newUser.setUpdatedAt(new Date());

            int result = userMapper.insert(newUser);

            if (result > 0) {
                // 如果注册时提供了角色ID，分配角色；否则默认分配普通用户角色（role_id = 2）
                if (userVo.getRoleIds() != null && !userVo.getRoleIds().isEmpty()) {
                    userMapper.insertUserRolesByUserId(newUser.getUserId(), userVo.getRoleIds());
                } else {
                    userMapper.insertUserRolesByUserId(newUser.getUserId(), Arrays.asList(2));
                }
                return BasicMsg.success("注册成功");
            } else {
                return BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "注册失败");
            }

        } catch (Exception e) {
            return BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "注册失败: " + e.getMessage());
        }
    }

    @Override
    public BasicMsg getAllUsers() {
        try {
            List<User> users = userMapper.selectAllUsers();
            return BasicMsg.success(users);
        } catch (Exception e) {
            return BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "获取用户列表失败: " + e.getMessage());
        }
    }

    @Override
    public BasicMsg deleteUser(String username) {
        try {
            // 先删除用户角色关系
            userMapper.deleteUserRoles(username);
            // 再删除用户
            int result = userMapper.deleteUser(username);

            if (result > 0) {
                return BasicMsg.success("用户删除成功");
            } else {
                return BasicMsg.fail(GlobalEnum.ErrorCode.USER_NOT_EXISTS, "用户不存在");
            }
        } catch (Exception e) {
            return BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "删除失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public BasicMsg addUserWithRoles(UserVo userVo) {
        try {
            // 先插入用户
            User newUser = new User();
            newUser.setUsername(userVo.getUsername());
            newUser.setPassword(userVo.getPassword());
            newUser.setEmail(userVo.getEmail());
            newUser.setRealName(userVo.getRealName());
            newUser.setPhone(userVo.getPhone());
            newUser.setCreatedAt(new Date());
            newUser.setUpdatedAt(new Date());

            int result = userMapper.insert(newUser);

            if (result > 0 && userVo.getRoleIds() != null && !userVo.getRoleIds().isEmpty()) {
                // 使用用户ID插入角色关系
                userMapper.insertUserRolesByUserId(newUser.getUserId(), userVo.getRoleIds());
            }

            return BasicMsg.success("用户添加成功");
        } catch (Exception e) {
            return BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "添加用户失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public BasicMsg updateUserRoles(String username, List<Integer> roleIds) {
        try {
            // 先获取用户ID
            Integer userId = userMapper.getUserIdByUsername(username);
            if (userId == null) {
                return BasicMsg.fail(GlobalEnum.ErrorCode.USER_NOT_EXISTS, "用户不存在");
            }

            // 先删除原有角色
            userMapper.deleteUserRoles(username);

            // 插入新角色
            if (roleIds != null && !roleIds.isEmpty()) {
                userMapper.insertUserRolesByUserId(userId, roleIds);
            }

            return BasicMsg.success("用户角色更新成功");
        } catch (Exception e) {
            return BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "更新用户角色失败: " + e.getMessage());
        }
    }

    @Override
    public BasicMsg getUserWithRolesByUsername(String username) {
        try {
            User user = userMapper.selectUserWithRoles(username);
            if (user != null) {
                UserVo userVo = new UserVo();
                userVo.setUserId(user.getUserId());
                userVo.setUsername(user.getUsername());
                userVo.setEmail(user.getEmail());
                userVo.setRealName(user.getRealName());
                userVo.setPhone(user.getPhone());

                // 获取用户角色并设置到返回对象中
                List<String> roles = userMapper.selectRolesByUsername(username);
                userVo.setRoles(roles);

                return BasicMsg.success(userVo);
            } else {
                return BasicMsg.fail(GlobalEnum.ErrorCode.USER_NOT_EXISTS, "用户不存在");
            }
        } catch (Exception e) {
            return BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "查询用户失败: " + e.getMessage());
        }
    }

    @Override
    public BasicMsg getUserRoles(String username) {
        try {
            List<String> roles = userMapper.selectRolesByUsername(username);
            return BasicMsg.success(roles);
        } catch (Exception e) {
            return BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "查询用户角色失败: " + e.getMessage());
        }
    }

    @Override
    public BasicMsg updateUser(UserVo userVo) {
        try {
            userMapper.updateUser(userVo);
            return BasicMsg.success("用户信息更新成功");
        } catch (Exception e) {
            return BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "更新用户信息失败: " + e.getMessage());
        }
    }
}